<template>
  <div class="container">
    <div class="app-container">
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true">
          添加角色
        </el-button>
      </div>
      <!-- 角色列表 -->
      <el-table :data="list">
        <el-table-column
          label="角色"
          align="center"
          width="200px"
          prop="name"
        >
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="启用" align="center" width="200px" prop="state">
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" size="mini" />
            <span v-else>{{
              row.state === 1 ? '启用' : row.state === 0 ? '未启用' : '未知'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center" prop="description">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" size="mini" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">

          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="upRole(row)"> 修改</el-button>
              <el-button size="mini" @click="row.isEdit = false"> 取消 </el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)"> 分配权限 </el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)"> 编辑 </el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="deleteRole(row.id)">
                <el-button slot="reference" size="mini" type="text" style="margin-left: 10px"> 删除 </el-button>
              </el-popconfirm>
            </template>
          </template>

        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" align="middle" style="height: 60px">
        <el-pagination
          layout="prev, pager, next"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 添加角色 -->
    <el-dialog
      title="新增角色"
      :visible.sync="showDialog"
      width:="500px"
      @close="close"
    >
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="roleForm.name"
            style="width: 80%"
            size="mini"
          />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <!-- 重置表单数据 需要prop属性 -->
          <!-- 如果不需要校验 就不需要写 prop属性 -->
          <el-switch
            v-model="roleForm.state"
            active-value="1"
            inactive-value="0"
            size="mini"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            style="width: 80%"
            size="mini"
            :rows="3"
          />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button size="mini" type="primary" @click="addRole">确定</el-button>
              <el-button size="mini" @click="close">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogVisible"
      title="分配权限"
>
      <el-tree
       ref="tree"
      :props="props"
        :data="treeData"
        default-expand-all
        show-checkbox
        node-key="id"
        :default-checked-keys="permIds"
        check-strictly
        />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="dialogVisible = false">取消</el-button>
      </el-col>
  </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, addRole, updateRole, deleteRole, getRoleDetail, assignPermission } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      pageParams: {
        page: 1,
        pagesize: 4,
        total: 0
      },
      showDialog: false,
      roleForm: {
        name: '',
        state: '1',
        description: ''
      },
      // 表单校验
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      treeData: [], // 弹出框 树形结构数据
      dialogVisible: false, // 分配权限 弹出框显示隐藏
      props: {
        label: 'name'
      },
      permIds: [], // 默认选中的权限点id
      currentRoleId: null // 当前选中的角色id

    }
  },
  computed: {
    // 获取角色列表
    roleList() {
      return this.list
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取-分页查询角色列表
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      this.list = rows
      // 增加一个编辑属性
      this.list.forEach(item => {
        // item.isEdit = false // 添加一个属性 初始值为false
        // 数据响应式的问题  数据变化 视图更新
        // 添加的动态属性 不具备响应式特点
        // this.$set(目标对象, 属性名称, 初始值) 可以针对目标对象 添加的属性 添加响应式
        this.$set(item, 'isEdit', false)
        // 新增缓存属性
        this.$set(item, 'editRow', {
          name: item.name,
          description: item.description,
          state: item.state
        })
      })
      this.pageParams.total = total
    },
    changePage(newPage) {
      this.pageParams.page = newPage
      this.getRoleList()
    },
    // 重置表单
    close() {
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    // 添加角色
    addRole() {
      this.$refs.roleForm.validate(async valid => {
        if (valid) {
          // 校验通过
          await addRole(this.roleForm)
          this.$message.success('添加成功')
          this.close()
          this.getRoleList()
        } else {
          this.$message.error('请输入必填项')
        }
      })
    },
    // 编辑角色
    btnEditRow(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.description = row.description
      row.editRow.state = row.state
    },
    // 修改角色信息
    async upRole(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRole({ id: row.id, ...row.editRow })
        this.$message.success('修改成功')
        // 更新显示数据  退出编辑状态
        // row.name = row.editRow.name // eslint的一校验 误判
        // Object.assign(target(目标对象), source(其属性将被合并到目标对象中))
        Object.assign(row, {
          ...row.editRow, // 退出编辑模式
          isEdit: false// 规避eslint的误判
        })
      } else {
        this.$message.error('请输入必填项')
      }
    },
    // 删除角色
    async deleteRole(id) {
      if (this.list.length === 1) {
        await deleteRole(id)
        this.$message.success('删除成功')
        this.pageParams.page = this.pageParams.page - 1
        this.getRoleList()
      } else {
        await deleteRole(id)
        this.$message.success('删除成功')
        this.getRoleList()
      }
    },
    // 分配权限
    async btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      // 获取权限 树状列表
      this.treeData = transListToTreeData(await getPermissionList(), 0)
      this.dialogVisible = true
    },
    // 保存权限
    async btnPermissionOK() {
      await assignPermission({
        id: this.currentRoleId,
        permIds: this.$refs.tree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.dialogVisible = false
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
